package com.strive.village.security;

import cn.hutool.core.util.StrUtil;
import com.strive.village.entity.SysUser;
import com.strive.village.service.SysUserService;
import com.strive.village.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author: strivePeng
 * @CreateTime: 2024年03月21日
 * @Description: jwt 拦截器
 **/

public class JwtAuthenticationFilter extends BasicAuthenticationFilter {

    @Autowired
    JwtUtils jwtUtils;

    // 由于要获取用户权限 首先调用userservice获取用户ID
    @Autowired
    SysUserService sysUserService;

    @Autowired
    UserDetailServiceImpl userDetailService;

    public JwtAuthenticationFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }

    /**
     * 重写方法实现jwt的解析
     */
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String jwt = request.getHeader(jwtUtils.getHeader());
        if (StrUtil.isBlankOrUndefined(jwt)) {
            filterChain.doFilter(request, response);
            return;
        }
        Claims claims = jwtUtils.getClaimByToken(jwt);
        // 没有jwt就会返回空
        if (claims == null) {
            throw new JwtException("token 异常");
        }
        if (jwtUtils.isTokenExpired(claims)) {
            throw new JwtException("token 已过期");
        }

        // 合法情况
        String username = claims.getSubject();
        SysUser user = sysUserService.getByUsername(username);
        // 获取用户权限等信息
        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username, null, userDetailService.getUserAuthority(user.getId()));
        // 上下文设置认证主体 就是token
        SecurityContextHolder.getContext().setAuthentication(token);
        filterChain.doFilter(request, response);
    }
}
